/*
 * @Date         : 2022-07-18 17:25:13
 * @LastEditors  : zu1662
 * @LastEditTime : 2022-07-18 22:26:02
 * @Description  : IP 地址帮助服务
 * 
 * Copyright © 2022 by zu1662, All Rights Reserved. 
 */
import { Injectable } from "@nestjs/common";
import IP2Region from "ip2region";


@Injectable()
export class HelpeIPService {

  // 获取客户端IP地址
  getClientIP(req): string {
    const ip =
      req.headers['x-real-ip'] ||
      req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
      (req.connection && req.connection.remoteAddress) || // 判断 connection 的远程 IP
      (req.socket && req.socket.remoteAddress) || // 判断后端的 socket 的 IP
      (req.connection && req.connection.socket && req.connection.socket.remoteAddress);
    
    return ip ? ip.split(':').pop() : '';
  }

  // IP 地址转 区域
  ipToRegion(ip): string {
    const query = new IP2Region({ disableIpv6: true });
    const result = query.search(ip);
    if(ip === '127.0.0.1') return result.isp
    if(result) return `${result.country} ${result.province} ${result.city} ${result.isp}`
    return ''
  }
}
